from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from skran.models import Project, Sprint, Task, PLANNING_HISTORY, GOAL, NOT_GOAL,\
    History
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required

import logging
from tagging.models import Tag


LOG = logging.getLogger(__name__)

"""
"""
@login_required
def sprint(request,id_project):

    project = Project.objects.get(pk=id_project)
    sprints = Sprint.objects.filter(project=id_project).order_by('-create_date')
    
    #Check if has at least one sprint for this project
    if not sprints:
        return render_to_response('no-sprints.html',locals(), context_instance=RequestContext(request))
    
    last_sprint = sprints[0]
    
    task_history = Task.objects.select_related('history').filter(history__id__exact=id_project).order_by('history_priority')

    if request.method == 'POST':
        sprint_post(request,id_project)        
    elif request.method == 'GET':
        sprint_get(request,id_project)
    
    if last_sprint.sprint_status != GOAL or last_sprint.sprint_status != NOT_GOAL:
        return HttpResponseRedirect(last_sprint.sprint_url_status());
    else:
        return render_to_response('sprint-dashboard.html',locals(), context_instance=RequestContext(request))

def sprint_get(request,id_project):
    pass

def sprint_post(request,id_project):
    pass

###################################################################################################
#                                   SMART INPUT SEARCH
###################################################################################################
@login_required
def get_tags(request,id_project):
    tags = Tag.objects.usage_for_model(History,filters=dict(project__id=id_project))

    json = "{"
    i = 0 
    for tag in tags:
        json+="\""+str(i)+"\":\"" + tag.name + "\""
        if i < len(tags)-1:
            json+=","
        i+=1
        
    if i != 0 or tags == []:
        json+="}"
        
    return HttpResponse(json)


